// DormitoryManagement.tsx
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { 
  Table, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  message, 
  Card, 
  Row, 
  Col,
  Tag,
  Select
} from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  TeamOutlined,
  HomeOutlined,
  UserOutlined
} from '@ant-design/icons';

const { TextArea } = Input;

interface DormBuilding {
  id: number;
  name: string;
  description: string;
  genderType?: 'male' | 'female'; // 宿舍类型：男生/女生
  totalRooms: number;
  createdTime: string;
}

interface Student {
  id: number;
  name: string;
  studentId: string;
  gender?: string; // 学生性别：'男' 或 '女'
  className: string;
  college: string;
  phone: string;
  dormBuilding?: string;
  dormRoom?: string;
  bedNumber?: number;
}

interface DormMember {
  id: number;
  name: string;
  studentId: string;
  bedNumber: number;
  key?: number;
}

interface Dormitory {
  id: number;
  buildingId: number;
  buildingName: string;
  roomNumber: string;
  genderType?: 'male' | 'female'; // 宿舍类型：男生/女生
  maxCapacity: number;
  currentCount: number;
  roomStatus: number;
  members?: DormMember[];
  createdTime: string;
}

interface SelectOption {
  value: string | number;
  label: string;
}

interface CustomSelectProps {
  value?: string | number;
  onChange?: (value: string | number) => void;
  options: SelectOption[];
  placeholder?: string;
  style?: React.CSSProperties;
}

const DormitoryManagement: React.FC = () => {
  const { t } = useTranslation('dormitory');
  const [buildings, setBuildings] = useState<DormBuilding[]>([]);
  const [dormitories, setDormitories] = useState<Dormitory[]>([]);
  const [allStudents, setAllStudents] = useState<Student[]>([]);
  const [loading, setLoading] = useState(false);
  const [buildingModalVisible, setBuildingModalVisible] = useState(false);
  const [roomModalVisible, setRoomModalVisible] = useState(false);
  const [memberModalVisible, setMemberModalVisible] = useState(false);
  const [editingBuilding, setEditingBuilding] = useState<DormBuilding | null>(null);
  const [editingRoom, setEditingRoom] = useState<Dormitory | null>(null);
  const [currentRoomMembers, setCurrentRoomMembers] = useState<Dormitory | null>(null);
  const [buildingForm] = Form.useForm();
  const [roomForm] = Form.useForm();
  const [memberForm] = Form.useForm();
  const [pagination, setPagination] = useState<TablePaginationConfig>({ 
    current: 1, 
    pageSize: 10, 
    total: 0 
  });
  const [activeTab, setActiveTab] = useState<'buildings' | 'rooms'>('buildings');

  // 获取宿舍楼列表
  const fetchBuildings = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const response = await fetch(
        `/api/dormitories/buildings?page=${page}&pageSize=${pageSize}`
      );
      const data = await response.json();
      
      if (data && data.data) {
        setBuildings(data.data);
      } else {
        setBuildings([]);
      }
      
      setPagination(prev => ({
        ...prev,
        current: data?.pagination?.current || page,
        total: data?.pagination?.total || 0,
        pageSize: data?.pagination?.pageSize || pageSize
      }));
    } catch (error) {
      console.error('获取宿舍楼列表失败:', error);
      message.error('获取宿舍楼列表失败');
      setBuildings([]);
    } finally {
      setLoading(false);
    }
  };

  // 获取宿舍房间列表
  const fetchDormitories = async (page = 1, pageSize = 10) => {
  setLoading(true);
  try {
    const response = await fetch(
      `/api/dormitories/rooms?page=${page}&pageSize=${pageSize}`
    );
    const data = await response.json();
    
    if (data && data.data) {
      // 确保先获取学生数据，然后再处理宿舍数据
      const students = await fetchAllStudents();
      
      const dormitoriesWithMembers = data.data.map((dorm: any) => {
        // 根据宿舍信息匹配学生
        const roomMembers = students.filter((student: Student) => 
          student.dormBuilding === dorm.buildingName && 
          student.dormRoom === dorm.roomNumber
        ).map((student: Student, index: number) => ({
          id: student.id,
          name: student.name,
          studentId: student.studentId,
          bedNumber: student.bedNumber || (index + 1)
        }));
        
        return {
          id: dorm.id,
          buildingId: dorm.buildingId || 0,
          buildingName: dorm.buildingName,
          roomNumber: dorm.roomNumber,
          genderType: dorm.genderType, // 包含性别类型
          maxCapacity: dorm.maxCapacity || dorm.totalBeds || 4,
          currentCount: roomMembers.length,
          roomStatus: roomMembers.length >= (dorm.maxCapacity || dorm.totalBeds || 4) ? 2 : 1,
          members: roomMembers,
          createdTime: dorm.createdTime || dorm.createdAt
        };
      });
      
      setDormitories(dormitoriesWithMembers);
    } else {
      setDormitories([]);
    }
    
    setPagination(prev => ({
      ...prev,
      current: data?.pagination?.current || page,
      total: data?.pagination?.total || 0,
      pageSize: data?.pagination?.pageSize || pageSize
    }));
  } catch (error) {
    console.error('获取宿舍列表失败:', error);
    message.error('获取宿舍列表失败');
    setDormitories([]);
  } finally {
    setLoading(false);
  }
};

  // 获取所有学生（与学生管理组件使用相同的数据获取方式）
  const fetchAllStudents = async (): Promise<Student[]> => {
  try {
    // 为了获取所有学生，不设置分页限制或使用较大的pageSize
    const params = new URLSearchParams({
      page: '1',
      pageSize: '1000' // 设置较大值以获取所有学生
    });
    
    const url = `/api/students?${params.toString()}`;
    console.log('获取学生数据URL:', url);
    
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`获取学生数据失败: ${response.status}`);
    }
    
    const data = await response.json();
    const students = data.data || data;
    setAllStudents(students);
    console.log('获取到的学生数量:', students.length);
    return students;
  } catch (error) {
    console.error('获取学生列表失败:', error);
    message.error('获取学生列表失败');
    setAllStudents([]);
    return [];
  }
};

  // 分页变化处理
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    const current = newPagination.current || 1;
    const pageSize = newPagination.pageSize || 10;
    
    if (activeTab === 'buildings') {
      fetchBuildings(current, pageSize);
    } else {
      fetchDormitories(current, pageSize);
    }
  };

  // 获取所有宿舍楼（用于下拉框）
  const fetchAllBuildings = async (): Promise<DormBuilding[]> => {
    try {
      const response = await fetch('/api/dormitories/buildings/all');
      const data = await response.json();
      return data;
    } catch {
      message.error('获取宿舍楼列表失败');
      return [];
    }
  };

  // 删除宿舍楼
  const handleDeleteBuilding = async (id: number, name: string) => {
    const isConfirmed = window.confirm(`${t('confirmDeleteBuilding')} "${name}" 吗？${t('irreversible')}`);
    
    if (!isConfirmed) {
      return;
    }

    try {
      const response = await fetch(`/api/dormitories/buildings/${id}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        message.success(t('deleteSuccess'));
        fetchBuildings();
      } else {
        const errorData = await response.json();
        message.error(errorData.error || '删除失败');
      }
    } catch {
      message.error('删除失败');
    }
  };

  // 删除宿舍房间
  const handleDeleteRoom = async (id: number, buildingName: string, roomNumber: string) => {
    const isConfirmed = window.confirm(`${t('confirmDeleteRoom')} "${buildingName} ${roomNumber}" 吗？${t('irreversible')}`);
    
    if (!isConfirmed) {
      return;
    }

    try {
      const response = await fetch(`/api/dormitories/rooms/${id}`, {
        method: 'DELETE',
      });

      const result = await response.json();

      if (response.ok && result.success) {
        message.success(t('deleteSuccess'));
        fetchDormitories();
      } else {
        message.error(result.error || t('deleteFailed'));
      }
    } catch {
      message.error('删除失败');
    }
  };

  // 宿舍楼列定义
  const buildingColumns: ColumnsType<DormBuilding> = [
    {
      title: t('buildingNameColumn'),
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '宿舍类型',
      dataIndex: 'genderType',
      key: 'genderType',
      render: (genderType: string) => {
        if (genderType === 'male') return <Tag color="blue">男生宿舍</Tag>;
        if (genderType === 'female') return <Tag color="pink">女生宿舍</Tag>;
        return <Tag>未设置</Tag>;
      },
    },
    {
      title: t('descriptionColumn'),
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: t('totalRoomsColumn'),
      dataIndex: 'totalRooms',
      key: 'totalRooms',
    },
    {
      title: t('createdTime'),
      dataIndex: 'createdTime',
      key: 'createdTime',
      render: (time: string) => new Date(time).toLocaleDateString(),
    },
    {
      title: t('operation'),
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEditBuilding(record)}
          >
            {t('edit')}
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteBuilding(record.id, record.name)}
          >
            {t('delete')}
          </Button>
        </Space>
      ),
    },
  ];

  // 宿舍房间列定义
  const roomColumns: ColumnsType<Dormitory> = [
    {
      title: t('building'),
      dataIndex: 'buildingName',
      key: 'buildingName',
    },
    {
      title: t('roomNumberColumn'),
      dataIndex: 'roomNumber',
      key: 'roomNumber',
    },
    {
      title: t('capacity'),
      dataIndex: 'maxCapacity',
      key: 'maxCapacity',
      render: (max: number, record: Dormitory) => (
        <span>{record.currentCount} / {max}</span>
      ),
    },
    {
    title: t('common:status'),
    dataIndex: 'roomStatus',
    key: 'roomStatus',
    render: (status: number, record: Dormitory) => {
      const statusMap = {
        1: { text: t('available'), color: 'green' },
        2: { text: t('full'), color: 'red' },
        3: { text: t('maintenance'), color: 'orange' },
      };
      
      // 动态计算状态：如果当前人数 >= 最大容量，则显示已满
      const actualStatus = record.currentCount >= record.maxCapacity ? 2 : status;
      const statusInfo = statusMap[actualStatus as keyof typeof statusMap] || { text: t('common:notSet'), color: 'default' };
      
      return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
    },
  },
    {
      title: t('createdTime'),
      dataIndex: 'createdTime',
      key: 'createdTime',
      render: (time: string) => new Date(time).toLocaleDateString(),
    },
    {
      title: t('operation'),
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<TeamOutlined />}
            onClick={() => handleManageMembers({
              ...record,
              members: record.members || []
            })}
          >
            成员管理
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEditRoom(record)}
          >
            {t('edit')}
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteRoom(record.id, record.buildingName, record.roomNumber)}
          >
            {t('delete')}
          </Button>
        </Space>
      ),
    },
  ];

  // 处理新建宿舍楼
  const handleCreateBuilding = () => {
    setEditingBuilding(null);
    buildingForm.resetFields();
    setBuildingModalVisible(true);
  };

  // 处理编辑宿舍楼
  const handleEditBuilding = (building: DormBuilding) => {
    setEditingBuilding(building);
    buildingForm.setFieldsValue(building);
    setBuildingModalVisible(true);
  };

  // 提交宿舍楼表单
  const handleBuildingSubmit = async (values: Partial<DormBuilding>) => {
    try {
      const url = editingBuilding 
        ? `/api/dormitories/buildings/${editingBuilding.id}`
        : '/api/dormitories/buildings';
      
      const method = editingBuilding ? 'PUT' : 'POST';
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      if (response.ok) {
        message.success(editingBuilding ? t('updateSuccess') : t('createSuccess'));
        setBuildingModalVisible(false);
        fetchBuildings();
      } else {
        const errorData = await response.json();
        message.error(errorData.error || t('operationFailed'));
      }
    } catch {
      message.error(t('operationFailed'));
    }
  };

  // 处理新建宿舍房间
  const handleCreateRoom = async () => {
    setEditingRoom(null);
    roomForm.resetFields();
    
    // 获取所有宿舍楼用于下拉框
    const allBuildings = await fetchAllBuildings();
    if (allBuildings.length > 0) {
      roomForm.setFieldsValue({
        buildingId: allBuildings[0].id,
        maxCapacity: 4,
        roomStatus: 1
      });
    }
    
    setRoomModalVisible(true);
  };

  // 处理编辑宿舍房间
  const handleEditRoom = (room: Dormitory) => {
    setEditingRoom(room);
    
    roomForm.setFieldsValue({
      buildingId: room.buildingId,
      roomNumber: room.roomNumber,
      maxCapacity: room.maxCapacity || 4, 
      roomStatus: room.roomStatus || 1
    });
    setRoomModalVisible(true);
  };

  // 提交宿舍房间表单
  const handleRoomSubmit = async (values: any) => {
    try {
      const maxCapacity = Number(values.maxCapacity);
      if (isNaN(maxCapacity) || maxCapacity < 1 || maxCapacity > 8) {
        message.error(t('capacityBetween'));
        return;
      }

      const building = buildings.find(b => b.id === values.buildingId);
      if (!building) {
        message.error(t('pleaseSelectValidBuilding'));
        return;
      }

      const requestData = {
        buildingName: building.name,
        roomNumber: values.roomNumber,
        maxCapacity: maxCapacity,
        roomStatus: values.roomStatus || 1
      };

      console.log('提交宿舍数据:', requestData);

      const url = editingRoom 
        ? `/api/dormitories/rooms/${editingRoom.id}`
        : '/api/dormitories/rooms';
      
      const method = editingRoom ? 'PUT' : 'POST';
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestData),
      });

      const result = await response.json();

      if (response.ok && result.success) {
        message.success(editingRoom ? t('updateSuccess') : t('createSuccess'));
        setRoomModalVisible(false);
        fetchDormitories();
      } else {
        message.error(result.error || t('operationFailed'));
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error(t('operationFailed'));
    }
  };

  // 管理宿舍成员
  const handleManageMembers = async (room: Dormitory) => {
  // 确保性别类型正确设置（从宿舍或宿舍楼获取）
  let genderType = room.genderType;
  if (!genderType && room.buildingName && buildings && buildings.length > 0) {
    const building = buildings.find(b => b.name === room.buildingName);
    if (building) {
      genderType = building.genderType;
    }
  }
  
  // 设置当前房间成员信息，包含性别类型
  setCurrentRoomMembers({
    ...room,
    genderType: genderType || room.genderType
  });
  
  // 确保获取最新的学生数据
  const students = await fetchAllStudents();
  
  // 重新计算当前宿舍的成员
  const currentRoomMembersList = students.filter((student: Student) => 
    student.dormBuilding === room.buildingName && 
    student.dormRoom === room.roomNumber
  ).map((student: Student, index: number) => ({
    id: student.id,
    name: student.name,
    studentId: student.studentId,
    bedNumber: student.bedNumber || (index + 1)
  }));
  
  // 初始化成员表单数据
  const initialMembers = currentRoomMembersList.map((member, index) => ({
    ...member,
    key: index
  }));
  
  memberForm.setFieldsValue({ members: initialMembers });
  setMemberModalVisible(true);
};

  // 处理选择学生 - 与学生管理组件保持一致的数据处理逻辑
  const handleStudentSelect = (studentId: string, index: number) => {
    console.log('选择学生ID:', studentId, '索引:', index);
    
    // 查找选中的学生 - 使用与StudentManagement组件相同的查询逻辑
    const selectedStudent = allStudents.find(student => student.studentId === studentId);
    
    if (selectedStudent) {
      console.log('找到学生:', selectedStudent.name, selectedStudent.studentId);
      const currentMembers = memberForm.getFieldValue('members') || [];
      
      // 确保当前成员数组有足够的长度
      while (currentMembers.length <= index) {
        currentMembers.push({});
      }
      
      // 更新成员信息 - 保持与StudentManagement组件一致的数据格式
      currentMembers[index] = {
        ...currentMembers[index],
        name: selectedStudent.name,
        studentId: selectedStudent.studentId,
        id: selectedStudent.id,
        // 保留已有的床位号，如果没有则尝试使用学生现有的床位号
        bedNumber: currentMembers[index].bedNumber || selectedStudent.bedNumber || ''
      };
      
      // 更新表单数据
      memberForm.setFieldsValue({ members: currentMembers });
      console.log('更新后的成员列表:', currentMembers);
    } else {
      console.error('未找到学生:', studentId);
    }
  };

  // 获取可用的学生选项 - 与学生管理组件保持一致的数据格式
  const getAvailableStudentOptions = (currentMembers: DormMember[] = []) => {
    // 添加安全检查，过滤掉 undefined 或缺少 studentId 的成员
    const currentStudentIds = currentMembers
      .filter(member => member && member.studentId)
      .map(member => member.studentId);
    
    console.log('当前成员学生ID列表:', currentStudentIds);
    console.log('当前宿舍信息:', currentRoomMembers?.buildingName, currentRoomMembers?.roomNumber);
    console.log('所有学生总数:', allStudents.length);
    
    // 获取当前宿舍的性别类型
    let dormGenderType: 'male' | 'female' | undefined;
    if (currentRoomMembers) {
      // 首先从宿舍本身获取类型
      dormGenderType = currentRoomMembers.genderType;
      
      // 如果宿舍没有类型，从宿舍楼列表获取（同步方式）
      if (!dormGenderType && currentRoomMembers.buildingName && buildings && buildings.length > 0) {
        const building = buildings.find(b => b.name === currentRoomMembers?.buildingName);
        if (building) {
          dormGenderType = building.genderType;
        }
      }
    }
    
    // 过滤可用学生 - 与学生管理组件保持一致的数据格式和过滤逻辑
    const availableStudents = allStudents.filter(student => {
      // 确保学生对象有效
      if (!student || !student.studentId) {
        return false;
      }
      
      // 验证学生性别与宿舍类型是否匹配
      if (dormGenderType && student.gender) {
        // 处理不同的性别格式：'男'/'女' 或 'Male'/'Female' 或 'male'/'female'
        let studentGenderType: 'male' | 'female' | undefined;
        const gender = String(student.gender).toLowerCase();
        if (gender === '男' || gender === 'male') {
          studentGenderType = 'male';
        } else if (gender === '女' || gender === 'female') {
          studentGenderType = 'female';
        }
        
        if (studentGenderType && studentGenderType !== dormGenderType) {
          // 性别不匹配，但如果在当前成员列表中，仍然允许（允许编辑现有成员，但会显示后端验证错误）
          const isInCurrentMembers = currentStudentIds.includes(student.studentId);
          if (!isInCurrentMembers) {
            console.log(`学生 ${student.name} 性别 ${student.gender} 与宿舍类型 ${dormGenderType} 不匹配，已过滤`);
            return false; // 性别不匹配且不在当前成员列表中，不允许选择
          }
        }
      }
      
      // 检查条件：
      // 1. 学生未分配宿舍
      // 2. 学生已经在当前宿舍（允许在表单中保留）
      // 3. 学生已经在当前成员列表中（允许在表单中保留）
      const isUnassigned = !student.dormBuilding || !student.dormRoom || student.dormBuilding === '' || student.dormRoom === '';
      const isInCurrentRoom = student.dormBuilding === currentRoomMembers?.buildingName && 
                              student.dormRoom === currentRoomMembers?.roomNumber;
      const isInCurrentMembers = currentStudentIds.includes(student.studentId);
      
      const result = isUnassigned || isInCurrentRoom || isInCurrentMembers;
      console.log(`学生 ${student.name} (${student.studentId}) 是否可用: ${result}`);
      return result;
    });
    
    console.log('过滤后可用学生数量:', availableStudents.length);
    
    // 按照学生管理组件的格式显示学生信息
    return availableStudents
      .sort((a, b) => a.studentId.localeCompare(b.studentId)) // 按学号排序
      .map(student => ({
        value: student.studentId,
        label: `${student.name} (${student.studentId}) - ${student.className || '暂无班级'}`
      }));
  };

  // 提交成员管理表单
  const handleMemberSubmit = async (values: { members: DormMember[] }) => {
  if (!currentRoomMembers) return;

  console.log('提交的成员数据:', values.members);

  try {
    const response = await fetch(`/api/dormitories/rooms/${currentRoomMembers.id}/members`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        members: values.members || []
      }),
    });

    const result = await response.json();
    console.log('服务器响应:', result);

    if (response.ok && result.success) {
      message.success(t('updateSuccess'));
      setMemberModalVisible(false);
      
      // 重新获取所有数据以确保一致性
      await fetchAllStudents();
      await fetchDormitories();
    } else {
      message.error(result.error || '更新失败');
    }
  } catch (error) {
    console.error('更新失败:', error);
    message.error('更新失败');
  }
};

  // 初始化数据
  useEffect(() => {
    const initializeData = async () => {
      if (activeTab === 'buildings') {
        await fetchBuildings();
      } else {
        // 先获取学生数据和宿舍楼数据，再获取宿舍数据
        await fetchAllStudents();
        await fetchAllBuildings().then(buildingList => {
          setBuildings(buildingList);
        });
        await fetchDormitories();
      }
    };
    
    initializeData();
  }, [activeTab]);

  // 原生 HTML 下拉框组件 - 与学生管理组件保持一致的数据格式和显示
  const StudentSelect: React.FC<{
    value?: string;
    onChange?: (value: string) => void;
    currentMembers?: DormMember[];
    placeholder?: string;
    style?: React.CSSProperties;
  }> = ({ value, onChange, currentMembers, placeholder, style }) => {
    const options = getAvailableStudentOptions(currentMembers);
    console.log('学生下拉框选项数量:', options.length);
    console.log('当前选中值:', value);

    const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
      const selectedValue = e.target.value;
      console.log('选择学生:', selectedValue);
      onChange?.(selectedValue);
    };

    return (
      <select
        value={value || ''}
        onChange={handleChange}
        style={{
          width: '100%',
          padding: '8px 12px',
          border: '1px solid #d9d9d9',
          borderRadius: '6px',
          fontSize: '14px',
          backgroundColor: 'white',
          ...style
        }}
      >
        <option value="">{placeholder || '请选择学生'}</option>
        {options.map(option => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
        {options.length === 0 && (
          <option disabled>暂无可用学生</option>
        )}
      </select>
    );
  };

  const CustomSelect: React.FC<CustomSelectProps> = ({ 
    value, 
    onChange, 
    options, 
    placeholder, 
    style 
  }) => {
    const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
      const newValue = e.target.value;
      
      if (newValue === '') {
        onChange?.('');
      } else {
        const numValue = Number(newValue);
        if (!isNaN(numValue) && isFinite(numValue)) {
          onChange?.(numValue);
        } else {
          onChange?.(newValue);
        }
      }
    };

    return (
      <select
        value={value}
        onChange={handleChange}
        style={{
          width: '100%',
          padding: '8px 12px',
          border: '1px solid #d9d9d9',
          borderRadius: '6px',
          fontSize: '14px',
          ...style
        }}
      >
        <option value="">{placeholder || '请选择'}</option>
        {options.map(option => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
    );
  };

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button 
              type={activeTab === 'buildings' ? 'primary' : 'default'}
              icon={<HomeOutlined />}
              onClick={() => setActiveTab('buildings')}
            >
              {t('buildingManagement')}
            </Button>
            <Button 
              type={activeTab === 'rooms' ? 'primary' : 'default'}
              icon={<TeamOutlined />}
              onClick={() => setActiveTab('rooms')}
            >
              {t('roomManagement')}
            </Button>
          </Space>
          
          <div style={{ float: 'right' }}>
            {activeTab === 'buildings' ? (
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleCreateBuilding}
              >
                {t('addBuilding')}
              </Button>
            ) : (
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleCreateRoom}
              >
                {t('addRoom')}
              </Button>
            )}
          </div>
        </div>

        {activeTab === 'buildings' ? (
          <Table
            columns={buildingColumns}
            dataSource={buildings}
            rowKey="id"
            loading={loading}
            pagination={pagination}
            onChange={handleTableChange}
          />
        ) : (
          <Table
            columns={roomColumns}
            dataSource={dormitories}
            rowKey="id"
            loading={loading}
            pagination={pagination}
            onChange={handleTableChange}
          />
        )}
      </Card>

      {/* 宿舍楼表单模态框 */}
      <Modal
        title={editingBuilding ? t('editBuilding') : t('addBuilding')}
        open={buildingModalVisible}
        onOk={() => buildingForm.submit()}
        onCancel={() => setBuildingModalVisible(false)}
        okText={t('ok')}
        cancelText={t('cancel')}
      >
        <Form
          form={buildingForm}
          layout="vertical"
          onFinish={handleBuildingSubmit}
        >
          <Form.Item
            name="name"
            label={t('buildingName')}
            rules={[{ required: true, message: t('pleaseInputBuildingName') }]}
          >
            <Input placeholder={t('pleaseInputBuildingName')} />
          </Form.Item>
          <Form.Item
            name="genderType"
            label="宿舍类型"
            rules={[{ required: true, message: '请选择宿舍类型' }]}
          >
            <Select placeholder="请选择宿舍类型">
              <Select.Option value="male">男生宿舍</Select.Option>
              <Select.Option value="female">女生宿舍</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="description"
            label={t('description')}
          >
            <TextArea placeholder={t('pleaseInputDescription')} rows={3} />
          </Form.Item>
          <Form.Item
            name="totalRooms"
            label={t('totalRooms')}
          >
            <Input type="number" placeholder={t('pleaseInputRoomCount')} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={editingRoom ? t('editRoom') : t('addRoom')}
        open={roomModalVisible}
        onOk={() => roomForm.submit()}
        onCancel={() => setRoomModalVisible(false)}
        okText={t('ok')}
        cancelText={t('cancel')}
        width={600}
      >
        <Form
          form={roomForm}
          layout="vertical"
          onFinish={handleRoomSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="buildingId"
                label={t('selectBuilding')}
                rules={[{ required: true, message: t('pleaseSelectBuilding') }]}
              >
                <CustomSelect
                  options={buildings.map(building => ({
                    value: building.id,
                    label: building.name
                  }))}
                  placeholder={t('pleaseSelectBuilding')}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="maxCapacity"
                label={t('maxCapacity')}
                rules={[
                  { required: true, message: t('pleaseInput') + t('maxCapacity') },
                  { 
                    validator: (_, value) => {
                      if (value === undefined || value === null || value === '') {
                        return Promise.reject(new Error(t('pleaseInput') + t('maxCapacity')));
                      }
                      const numValue = Number(value);
                      if (isNaN(numValue)) {
                        return Promise.reject(new Error(t('pleaseInputValidNumber')));
                      }
                      if (numValue < 1 || numValue > 8) {
                        return Promise.reject(new Error(t('capacityBetween')));
                      }
                      return Promise.resolve();
                    }
                  }
                ]}
                initialValue={4}
              >
                <Input 
                  type="number" 
                  placeholder={t('pleaseInput') + t('maxCapacity')} 
                  min={1} 
                  max={8} 
                  onChange={(e) => {
                    const value = e.target.value;
                    if (value === '' || /^\d+$/.test(value)) {
                      const numValue = value === '' ? '' : Number(value);
                      roomForm.setFieldValue('maxCapacity', numValue);
                    }
                  }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="roomNumber"
                label={t('roomNumberColumn')}
                rules={[{ required: true, message: t('pleaseInputRoomNumber') }]}
              >
                <Input placeholder={t('pleaseInputRoomNumber')} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="roomStatus"
                label={t('status')}
              >
                <CustomSelect
                  options={[
                    { value: 1, label: t('available') },
                    { value: 2, label: t('full') },
                    { value: 3, label: t('maintenance') }
                  ]}
                  placeholder={t('pleaseSelect') + t('status')}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 成员管理模态框 */}
      <Modal
        title={`${t('memberManagement')} - ${currentRoomMembers?.buildingName} ${currentRoomMembers?.roomNumber}`}
        open={memberModalVisible}
        onOk={() => memberForm.submit()}
        onCancel={() => setMemberModalVisible(false)}
        okText={t('ok')}
        cancelText={t('cancel')}
        width={800}
      >
        <div style={{ marginBottom: 16 }}>
          <span>{t('currentMembers')}: {currentRoomMembers?.currentCount || 0} / </span>
          <span>{t('maxCapacity')}: {currentRoomMembers?.maxCapacity || 0}</span>
        </div>
        
        <Form
          form={memberForm}
          layout="vertical"
          onFinish={handleMemberSubmit}
        >
          <Form.List name="members">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => {
                  const currentMembers = memberForm.getFieldValue('members') || [];
                  const currentMember = currentMembers[name] || {};
                  
                  return (
                    <Space key={key} style={{ display: 'flex', marginBottom: 16 }} align="baseline">
                      <Form.Item
                        {...restField}
                        name={[name, 'studentId']}
                        label="选择学生"
                        rules={[{ required: true, message: '请选择学生' }]}
                        style={{ marginBottom: 0 }}
                        initialValue={currentMember.studentId || ''}
                      >
                        <StudentSelect
                          value={currentMember.studentId}
                          onChange={(value) => handleStudentSelect(value, name)}
                          currentMembers={currentMembers}
                          placeholder="选择学生"
                          style={{ width: 200 }}
                        />
                      </Form.Item>
                      
                      <Form.Item
                        {...restField}
                        name={[name, 'name']}
                        label="姓名"
                        style={{ marginBottom: 0 }}
                        initialValue={currentMember.name || ''}
                      >
                        <Input 
                          placeholder="姓名" 
                          style={{ width: 120 }} 
                          readOnly 
                          prefix={<UserOutlined />}
                        />
                      </Form.Item>
                      
                      <Form.Item
                        {...restField}
                        name={[name, 'bedNumber']}
                        label="床位号"
                        rules={[
                          { required: true, message: '请输入床位号' },
                          { 
                            validator: (_, value) => {
                              // required 规则已经处理了空值，这里不需要再检查
                              if (!value) {
                                return Promise.resolve(); // 空值由 required 规则处理
                              }
                              const numValue = Number(value);
                              if (isNaN(numValue)) {
                                return Promise.reject(new Error(t('pleaseInputValidNumber')));
                              }
                              if (numValue < 1 || numValue > 8) {
                                return Promise.reject(new Error('床位号必须在1-8之间'));
                              }
                              // 检查床位号是否重复
                              const currentMembers = memberForm.getFieldValue('members') || [];
                              const bedNumberStr = String(value);
                              const duplicateIndex = currentMembers.findIndex((m: DormMember, idx: number) => 
                                idx !== name && m.bedNumber && String(m.bedNumber) === bedNumberStr
                              );
                              if (duplicateIndex !== -1) {
                                const duplicateMember = currentMembers[duplicateIndex];
                                return Promise.reject(new Error(`床位号${value}已被${duplicateMember.name || '其他成员'}使用`));
                              }
                              return Promise.resolve();
                            }
                          }
                        ]}
                        style={{ marginBottom: 0 }}
                        initialValue={currentMember.bedNumber || ''}
                      >
                        <Input 
                          type="number" 
                          placeholder="床位号" 
                          min={1} 
                          max={8} 
                          style={{ width: 100 }}
                        />
                      </Form.Item>
                      
                      <Button 
                        type="link" 
                        danger 
                        onClick={() => remove(name)}
                        style={{ marginTop: 24 }}
                      >
                        {t('delete')}
                      </Button>
                    </Space>
                  );
                })}
                <Form.Item>
                  <Button
                    type="dashed"
                    onClick={() => add()}
                    block
                    icon={<PlusOutlined />}
                    disabled={
                      fields.length >= (currentRoomMembers?.maxCapacity || 8) ||
                      (currentRoomMembers?.currentCount || 0) >= (currentRoomMembers?.maxCapacity || 8)
                    }
                  >
                    {fields.length >= (currentRoomMembers?.maxCapacity || 8) ||
                     (currentRoomMembers?.currentCount || 0) >= (currentRoomMembers?.maxCapacity || 8)
                      ? t('dormitoryFull')
                      : t('addMember')}
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </Modal>
    </div>
  );
};

export default DormitoryManagement;